﻿using UnityEditor;
using UnityEngine;

namespace GameBasic.Editors
{
    [CustomPropertyDrawer(typeof(ShowDictionaryAttribute))]
    public class ShowDictionaryAttributeDrawer : PropertyDrawer
    {
        float height;
        float keysHeight;
        float valuesHeight;

        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            ShowDictionaryAttribute att = attribute as ShowDictionaryAttribute;
            var pKeys = property.FindPropertyRelative("_keys");
            var pValues = property.FindPropertyRelative("_values");

            position.height = height;
            label.text = $"{label.text} ({pKeys.arraySize})";

            // Toggles
            Rect toggleRect = position;
            toggleRect.x = position.width - 32;
            toggleRect.width = 16;
            if (toggleRect.x > 32)
            {
                att.key = EditorGUI.Toggle(toggleRect, att.key);
                toggleRect.x += 16;
                att.value = EditorGUI.Toggle(toggleRect, att.value);
            }

            //
            if (att.key || att.value)
            {
                if (property.isExpanded = EditorGUI.Foldout(position, property.isExpanded, label))
                {
                    position.y += height;
                    EditorGUI.indentLevel++;

                    if (att.key)
                    {
                        position.height = keysHeight;
                        EditorGUI.PropertyField(position, pKeys, new GUIContent("Keys"), true);
                    }

                    if (att.value)
                    {
                        position.y += keysHeight;
                        position.height = valuesHeight;
                        EditorGUI.PropertyField(position, pValues, new GUIContent("Values"), true);
                    }

                    EditorGUI.indentLevel--;
                }
            }
            else
            {
                EditorGUI.LabelField(position, label);
            }
        }

        public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
        {
            ShowDictionaryAttribute att = attribute as ShowDictionaryAttribute;
            var pKeys = property.FindPropertyRelative("_keys");
            var pValues = property.FindPropertyRelative("_values");

            height = EditorGUI.GetPropertyHeight(property);
            keysHeight = 0;
            valuesHeight = 0;

            if (property.isExpanded)
            {
                if (att.key)
                    keysHeight = EditorGUI.GetPropertyHeight(pKeys);

                if (att.value)
                    valuesHeight = EditorGUI.GetPropertyHeight(pValues);
            }

            return height + keysHeight + valuesHeight;
        }
    }
}